<template>
  <div class="svg-preview">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <button class="back-btn" @click="goBack">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M19 12H5M12 19l-7-7 7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          返回图库
        </button>
        <h2 class="editor-title">{{ currentTitle }}</h2>
      </div>
      <div class="toolbar-right">
        <button class="format-btn" @click="formatSvg">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M4 7h3m0 0v10m0-10L10 4M4 17h3m0 0L10 20M20 7h-3m0 0v10m0-10L14 4M20 17h-3m0 0L14 20" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          格式化
        </button>
        <button class="save-btn" @click="saveToGallery">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <polyline points="17,21 17,13 7,13 7,21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <polyline points="7,3 7,8 15,8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          保存到图库
        </button>
        <button class="download-btn" @click="downloadSvg">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <polyline points="7,10 12,15 17,10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <line x1="12" y1="15" x2="12" y2="3" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
          下载
        </button>
      </div>
    </div>

    <!-- 主编辑区域 -->
    <div class="editor-container">
      <!-- 左侧代码编辑器 -->
      <div class="code-editor">
        <div class="editor-header">
          <h3>SVG 代码</h3>
          <div class="editor-actions">
            <button class="copy-btn" @click="copySvg">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <rect x="9" y="9" width="13" height="13" rx="2" ry="2" stroke="currentColor" stroke-width="2" fill="none"/>
                <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" stroke="currentColor" stroke-width="2" fill="none"/>
              </svg>
              复制
            </button>
            <button class="paste-btn" @click="pasteSvg">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" stroke="currentColor" stroke-width="2" fill="none"/>
                <rect x="8" y="2" width="8" height="4" rx="1" ry="1" stroke="currentColor" stroke-width="2" fill="none"/>
              </svg>
              粘贴
            </button>
            <button class="clear-btn" @click="clearEditor">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <polyline points="3,6 5,6 21,6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M10 11v6M14 11v6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
              清空
            </button>
          </div>
        </div>
        <div class="editor-content">
          <textarea
            ref="codeEditor"
            v-model="svgCode"
            @input="onCodeChange"
            placeholder="在此输入或粘贴 SVG 代码..."
            class="code-textarea"
            spellcheck="false"
          ></textarea>
          <div class="editor-info">
            <span class="line-info">行数：{{ lineCount }}</span>
            <span class="char-info">字符：{{ charCount }}</span>
            <span class="status-info" :class="{ 'error': hasError, 'success': !hasError && svgCode.length > 0 }">
              {{ statusText }}
            </span>
          </div>
        </div>
      </div>

      <!-- 右侧预览区域 -->
      <div class="preview-panel">
        <div class="preview-header">
          <h3>实时预览</h3>
          <div class="preview-actions">
            <button class="zoom-out-btn" @click="zoomOut">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <circle cx="11" cy="11" r="8" stroke="currentColor" stroke-width="2" fill="none"/>
                <path d="M21 21l-4.35-4.35" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <line x1="8" y1="11" x2="14" y2="11" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </button>
            <span class="zoom-level">{{ Math.round(zoomLevel * 100) }}%</span>
            <button class="zoom-in-btn" @click="zoomIn">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <circle cx="11" cy="11" r="8" stroke="currentColor" stroke-width="2" fill="none"/>
                <path d="M21 21l-4.35-4.35" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <line x1="11" y1="8" x2="11" y2="14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <line x1="8" y1="11" x2="14" y2="11" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </button>
            <button class="reset-zoom-btn" @click="resetZoom">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <polyline points="23,4 23,10 17,10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </button>
          </div>
        </div>
        <div class="preview-content">
          <div class="preview-area" :style="{ transform: `scale(${zoomLevel})` }">
            <div v-if="!hasError && svgCode.length > 0" class="svg-display" v-html="svgCode"></div>
            <div v-else-if="hasError" class="error-display">
              <div class="error-icon">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none">
                  <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none"/>
                  <line x1="15" y1="9" x2="9" y2="15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  <line x1="9" y1="9" x2="15" y2="15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
              <h4>SVG 代码错误</h4>
              <p>请检查您的 SVG 代码语法</p>
            </div>
            <div v-else class="empty-display">
              <div class="empty-icon">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="none">
                  <rect x="3" y="3" width="18" height="18" rx="2" ry="2" stroke="currentColor" stroke-width="2" fill="none"/>
                  <circle cx="8.5" cy="8.5" r="1.5" stroke="currentColor" stroke-width="2" fill="none"/>
                  <polyline points="21,15 16,10 5,21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
              <h4>开始编辑</h4>
              <p>在左侧输入 SVG 代码来查看预览</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 响应式数据
const svgCode = ref('')
const zoomLevel = ref(1)
const hasError = ref(false)
const codeEditor = ref(null)
const selectedSvg = ref(null)

// 计算属性
const lineCount = computed(() => {
  return svgCode.value.split('\n').length
})

const charCount = computed(() => {
  return svgCode.value.length
})

const statusText = computed(() => {
  if (svgCode.value.length === 0) return '等待输入'
  if (hasError.value) return '语法错误'
  return '语法正确'
})

const currentTitle = computed(() => {
  if (selectedSvg.value) {
    return `编辑 - ${selectedSvg.value.displayName}`
  }
  return 'SVG 编辑器'
})

// 方法
const goBack = () => {
  router.push('/')
}

const onCodeChange = () => {
  // 保存到 localStorage
  localStorage.setItem('svgPreviewCode', svgCode.value)
  
  // 验证 SVG 代码
  validateSvg()
}

const validateSvg = () => {
  if (svgCode.value.trim() === '') {
    hasError.value = false
    return
  }
  
  try {
    const parser = new DOMParser()
    const doc = parser.parseFromString(svgCode.value, 'image/svg+xml')
    const parserError = doc.querySelector('parsererror')
    
    if (parserError) {
      hasError.value = true
    } else {
      hasError.value = false
    }
  } catch (error) {
    hasError.value = true
  }
}

const formatSvg = () => {
  if (svgCode.value.trim() === '') return
  
  try {
    const parser = new DOMParser()
    const doc = parser.parseFromString(svgCode.value, 'image/svg+xml')
    const svgElement = doc.documentElement
    
    if (svgElement.tagName === 'svg') {
      const formatted = new XMLSerializer().serializeToString(svgElement)
      svgCode.value = formatted
        .replace(/></g, '>\n<')
        .replace(/^\s*\n/gm, '')
        .split('\n')
        .map((line, index) => {
          const depth = (line.match(/</g) || []).length - (line.match(/\//g) || []).length
          return '  '.repeat(Math.max(0, depth - 1)) + line.trim()
        })
        .join('\n')
    }
  } catch (error) {
    alert('格式化失败：SVG 代码存在语法错误')
  }
}

const copySvg = async () => {
  if (svgCode.value.trim() === '') return
  
  try {
    await navigator.clipboard.writeText(svgCode.value)
    alert('SVG 代码已复制到剪贴板')
  } catch (error) {
    alert('复制失败：无法访问剪贴板')
  }
}

const pasteSvg = async () => {
  try {
    const text = await navigator.clipboard.readText()
    svgCode.value = text
    validateSvg()
  } catch (error) {
    alert('粘贴失败：无法访问剪贴板')
  }
}

const clearEditor = () => {
  if (confirm('确定要清空编辑器吗？')) {
    svgCode.value = ''
    hasError.value = false
    selectedSvg.value = null
    localStorage.removeItem('selectedSvgForEdit')
  }
}

const zoomIn = () => {
  zoomLevel.value = Math.min(zoomLevel.value + 0.1, 3)
}

const zoomOut = () => {
  zoomLevel.value = Math.max(zoomLevel.value - 0.1, 0.1)
}

const resetZoom = () => {
  zoomLevel.value = 1
}

const saveToGallery = () => {
  if (svgCode.value.trim() === '' || hasError.value) {
    alert('请先输入有效的 SVG 代码')
    return
  }
  
  // 从 localStorage 获取现有的 SVG 文件
  const existingSvgs = JSON.parse(localStorage.getItem('svgGalleryFiles') || '[]')
  
  let newSvg
  
  if (selectedSvg.value) {
    // 如果是编辑现有的 SVG，更新它
    const index = existingSvgs.findIndex(svg => svg.id === selectedSvg.value.id)
    if (index !== -1) {
      existingSvgs[index] = {
        ...existingSvgs[index],
        content: svgCode.value,
        size: new Blob([svgCode.value]).size,
        uploadDate: new Date()
      }
      alert('SVG 已更新到图库！')
    } else {
      // 如果找不到原始 SVG，创建新的
      newSvg = {
        id: Date.now() + Math.random(),
        name: `edited-${selectedSvg.value.name}`,
        displayName: `已编辑 - ${selectedSvg.value.displayName}`,
        category: 'Custom',
        description: `基于 ${selectedSvg.value.displayName} 编辑的 SVG`,
        tags: ['custom', 'edited', ...selectedSvg.value.tags],
        content: svgCode.value,
        size: new Blob([svgCode.value]).size,
        isFavorited: false,
        uploadDate: new Date()
      }
      existingSvgs.push(newSvg)
      alert('编辑后的 SVG 已保存为新文件！')
    }
  } else {
    // 创建新的 SVG
    newSvg = {
      id: Date.now() + Math.random(),
      name: `custom-${Date.now()}.svg`,
      displayName: `Custom SVG ${new Date().toLocaleString()}`,
      category: 'Custom',
      description: '通过编辑器创建的自定义 SVG',
      tags: ['custom', 'created', 'editor'],
      content: svgCode.value,
      size: new Blob([svgCode.value]).size,
      isFavorited: false,
      uploadDate: new Date()
    }
    existingSvgs.push(newSvg)
    alert('SVG 已保存到图库！')
  }
  
  // 保存到 localStorage
  localStorage.setItem('svgGalleryFiles', JSON.stringify(existingSvgs))
  
  // 触发自定义事件通知图库更新
  window.dispatchEvent(new CustomEvent('svgGalleryUpdated'))
}

const downloadSvg = () => {
  if (svgCode.value.trim() === '' || hasError.value) {
    alert('请先输入有效的 SVG 代码')
    return
  }
  
  const blob = new Blob([svgCode.value], { type: 'image/svg+xml' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  
  // 使用选中的 SVG 名称或默认名称
  const filename = selectedSvg.value ? 
    `edited-${selectedSvg.value.name}` : 
    `custom-${Date.now()}.svg`
  
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}

const loadSelectedSvg = () => {
  const savedSvg = localStorage.getItem('selectedSvgForEdit')
  if (savedSvg) {
    try {
      selectedSvg.value = JSON.parse(savedSvg)
      svgCode.value = selectedSvg.value.content
      validateSvg()
      // 清理 localStorage 中的数据
      localStorage.removeItem('selectedSvgForEdit')
    } catch (error) {
      console.error('加载选中的 SVG 失败：', error)
    }
  }
}

// 生命周期
onMounted(() => {
  // 首先尝试加载选中的 SVG
  loadSelectedSvg()
  
  // 如果没有选中的 SVG，从 localStorage 加载保存的代码
  if (!selectedSvg.value) {
    const savedCode = localStorage.getItem('svgPreviewCode')
    if (savedCode) {
      svgCode.value = savedCode
      validateSvg()
    }
  }
  
  // 如果还是没有代码，使用示例代码
  if (svgCode.value === '') {
    svgCode.value = `<svg width="200" height="200" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
      <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
    </linearGradient>
  </defs>
  <circle cx="100" cy="100" r="80" fill="url(#gradient)" />
  <text x="100" y="105" text-anchor="middle" font-family="Arial, sans-serif" font-size="14" fill="white">Hello SVG</text>
</svg>`
    validateSvg()
  }
})

// 监听 SVG 代码变化
watch(svgCode, () => {
  validateSvg()
})
</script>

<style scoped>
.svg-preview {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e2e8f0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  background: #64748b;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.back-btn:hover {
  background: #475569;
}

.editor-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.format-btn, .save-btn, .download-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.format-btn {
  background: #f59e0b;
  color: white;
}

.format-btn:hover {
  background: #d97706;
}

.save-btn {
  background: #10b981;
  color: white;
}

.save-btn:hover {
  background: #059669;
}

.download-btn {
  background: #3b82f6;
  color: white;
}

.download-btn:hover {
  background: #2563eb;
}

.editor-container {
  flex: 1;
  display: flex;
  height: calc(100vh - 80px);
}

.code-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #1e293b;
  color: #e2e8f0;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #334155;
  border-bottom: 1px solid #475569;
}

.editor-header h3 {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
}

.editor-actions {
  display: flex;
  gap: 8px;
}

.copy-btn, .paste-btn, .clear-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: #475569;
  color: #e2e8f0;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.85rem;
  transition: all 0.2s;
}

.copy-btn:hover, .paste-btn:hover, .clear-btn:hover {
  background: #64748b;
}

.editor-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.code-textarea {
  flex: 1;
  padding: 20px;
  background: #1e293b;
  color: #e2e8f0;
  border: none;
  outline: none;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
}

.code-textarea::placeholder {
  color: #64748b;
}

.editor-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: #334155;
  border-top: 1px solid #475569;
  font-size: 0.85rem;
}

.line-info, .char-info {
  color: #94a3b8;
}

.status-info {
  font-weight: 500;
  color: #94a3b8;
}

.status-info.error {
  color: #ef4444;
}

.status-info.success {
  color: #10b981;
}

.preview-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-left: 1px solid #e2e8f0;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
}

.preview-header h3 {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
  color: #1e293b;
}

.preview-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.zoom-out-btn, .zoom-in-btn, .reset-zoom-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: #f1f5f9;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.zoom-out-btn:hover, .zoom-in-btn:hover, .reset-zoom-btn:hover {
  background: #e2e8f0;
}

.zoom-level {
  font-size: 0.85rem;
  color: #64748b;
  font-weight: 500;
  min-width: 50px;
  text-align: center;
}

.preview-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  overflow: auto;
}

.preview-area {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  transition: transform 0.3s ease;
}

.svg-display {
  max-width: 100%;
  max-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.svg-display svg {
  max-width: 100%;
  max-height: 100%;
  height: auto;
  width: auto;
}

.error-display, .empty-display {
  text-align: center;
  color: #64748b;
  padding: 40px;
}

.error-display {
  color: #ef4444;
}

.error-icon, .empty-icon {
  margin-bottom: 16px;
}

.error-display h4, .empty-display h4 {
  margin: 0 0 8px 0;
  font-size: 1.1rem;
  font-weight: 600;
}

.error-display p, .empty-display p {
  margin: 0;
  font-size: 0.9rem;
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }
  
  .toolbar-left, .toolbar-right {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }
  
  .editor-container {
    flex-direction: column;
    height: calc(100vh - 120px);
  }
  
  .code-editor, .preview-panel {
    flex: 1;
    min-height: 300px;
  }
  
  .preview-panel {
    border-left: none;
    border-top: 1px solid #e2e8f0;
  }
}
</style> 